/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package aso.upna.controllers;

import aso.upna.filesystem.SharedFolder;
import aso.upna.cancion.*;
import aso.upna.controllers.chains.LocalChain;
import aso.upna.controllers.chains.NameChain;
import aso.upna.controllers.chains.RemoteChain;
import aso.upna.playlist.GenericIterator;
import aso.upna.playlist.GenericList;
import java.io.File;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

/**
 *
 * @author triki
 */
public class SearchTableController {

    private JTable table;
    private GenericList local_list;
    private GenericList remote_list;
    private boolean show_local;
    private boolean show_remote;
    private GenericList lista;
    private String search_pattern;

    private NameChain name_c;
    private LocalChain local_c;
    private RemoteChain remote_c;

    public SearchTableController(JTable jTable)
    {
        table = jTable;
        show_local = false;
        show_remote = false;
        lista = new GenericList();
        search_pattern = new String();
    }

    public void setSearchPattern(String sp)
    {
        this.search_pattern = new String(sp);
    }

    public void registerList(GenericList list)
    {
        lista = list;
    }

    public void registerLocalList(GenericList local)
    {
        local_list = local;
    }

    public void registerRemoteList(GenericList remote)
    {
        remote_list = remote;
    }
    
    /*public void addElement(AbstractCancion cancion)
    {
        lista.addElement(cancion);
    }

    public void addElements(Vector elements)
    {
        lista.addElements(elements);
    }*/

    public void setShowLocal(boolean local)
    {
        show_local = local;
    }

    public void setShowRemote(boolean remote)
    {
        show_remote = remote;
    }
    
    public void refresh()
    {
        int rows,i,j;
       
        GenericIterator iter = null;
        File aux = null;
        String sAux = null;
        AbstractCancion can = null;
        Object obj[] = null;

        DefaultTableModel tab = (DefaultTableModel) table.getModel();
       
        rows = table.getRowCount();         

        cleanTable();
        GenericList lis = setPrefilter();
        System.out.println("HELLO");
        if(search_pattern != null)
        {
            System.out.println("ENTRA?");
            System.out.println("Search by: "+search_pattern);
            
            if(search_pattern.length() > 0)
            {
                System.out.println("ENTRA!");
                lis = searchByPattern(lis,search_pattern);
            }
        }
        
        iter = lis.getIterator();
        i=0;
        
        while(iter.hasNext())
        {
            if(i > rows-1)
            {
                tab.addRow(obj);
            }

            can = (AbstractCancion) iter.current();
            sAux = can.getFilename();
            aux = new File(can.getPath()+sAux);
            
            if(can.is_local())
            {
                table.setValueAt("Local",i, 0);
                table.setValueAt(" - ",i, 1);
            }
            else
            {
                table.setValueAt("Remota",i, 0);
                table.setValueAt(""+can.getPath(),i, 1);
            }

            table.setValueAt(can.getFilename(),i, 2);

            if(can.hasMetadata())
            {
                table.setValueAt(can.getMetadatos().getTitulo(),i, 3);
                table.setValueAt(can.getMetadatos().getGrupo(),i,4);
            }
            table.setValueAt(""+can.getDuracion(), i, 5);
            table.setValueAt(""+convertToMb(aux.length()), i, 6);
            i++;
            
            iter.next();
        }

        /*if(show_local)
        {
            iter = local_list.getIterator();            
            i=0;
            j=0;
            
            while(iter.hasNext())
            {
                if(i > rows-1)
                {
                    tab.addRow(obj);
                }

                can = (AbstractCancion) iter.current();

                sAux = can.getFilename();

                aux = new File(can.getPath()+sAux);

                table.setValueAt("Local",i, 0);
                table.setValueAt(" - ",i, 1);
                table.setValueAt(can.getMetadatos().getTitulo(),i, 2);
                table.setValueAt(""+can.getDuracion(), i, 3);
                table.setValueAt(""+convertToMb(aux.length()), i, 4);

                iter.next();
                i++;
            }
        }*/

    }

    public GenericList searchByPattern(GenericList lista,String search_pattern)
    {
        GenericIterator it = lista.getIterator();
        GenericList lis = new GenericList();
        CharSequence ch_aux;
        AbstractCancion c_aux;
        String s_aux;

        search_pattern = search_pattern.toLowerCase();

        while(it.hasNext())
        {           
            c_aux = (AbstractCancion)it.current();
            it.next();
            ch_aux = search_pattern.subSequence(0,search_pattern.length());

            //Buscamos en el nombre del archivo.
            s_aux = c_aux.getFilename();
            s_aux = s_aux.toLowerCase();
            
            if(s_aux.contains(ch_aux))
            {
                lis.addElement(c_aux);
                continue;
            }

            if(!c_aux.hasMetadata())
                continue;

            if(c_aux.getMetadatos().getTitulo().contains(ch_aux))
            {
                lis.addElement(c_aux);
                continue;
            }

            if(c_aux.getMetadatos().getGrupo().contains(ch_aux))
            {
                lis.addElement(c_aux);
                continue;
            }

            if(c_aux.getMetadatos().getAlbum().contains(ch_aux))
            {
                lis.addElement(c_aux);
                continue;
            }
        }
        
        return lis;
    }
    private GenericList setPrefilter()
    {
        GenericList list = new GenericList();
        GenericIterator it = lista.getIterator();
        AbstractCancion cancion = null;

        //Miramos las canciones remotas y locales
        
        while(it.hasNext())
        {
            cancion = (AbstractCancion) it.current();
            
            if(cancion.is_local() && show_local)
                list.addElement(cancion);

            if(!cancion.is_local() && show_remote)
                list.addElement(cancion);

            it.next();
        }

        //una vez que ya tenemos la lista general. Recorremos los metadatos
        //buscando canciones en las que coincida dicha palabra clave.
        //Miramos en todos los metadatos. (titulo, grupo y album)
        return list;
    }

    private void cleanTable()
    {
        int rows,cols,i,j;
        rows = table.getRowCount();
        cols = table.getColumnCount();

        for(i=0;i<rows;i++)
        {
            for(j=0;j<cols;j++)
            {
                table.setValueAt("", i, j);
            }
        }
    }

    private Vector getSelectedRows()
    {
        int num_rows,j;
        Vector v = new Vector();

        num_rows = table.getSelectedRowCount();

        if(num_rows > 0)
        {
            return v;
        }
        else
            return null;
    }

    private static String convertToMb(long bytes)
    {
        if(bytes == 0)
            return "0 Mb";
        
        float mb = (float)bytes/(1024*1024);
        String aux = new String(""+mb);
        int pos = aux.indexOf(".");

        return ""+aux.substring(0, pos+3)+" Mb";
    }
}
